﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;

namespace ABDLight
{
    public partial class frmSettings : Form
    {

        public frmSettings()
        {
            InitializeComponent();
        }

      
        private void edSave_Click(object sender, EventArgs e)
        {

            if (!TestConnection())
            {
                this.DialogResult = DialogResult.Retry;
                return;
            }


            //==== Сохранение параметров (окно настроек) (frmSettings)
            ((frmMine)this.Owner).cfg.Login = edLogin.Text;
            ((frmMine)this.Owner).cfg.edPass = edPass.Text;
            ((frmMine)this.Owner).cfg.TmpDir = edTmpDir.Text;
            ((frmMine)this.Owner).cfg.defCountry = cmbCountry.SelectedIndex;

            /*
            ((frmMine)this.Owner).cfg.CheckEmail =  ed_CheckMail.Text ;
            ((frmMine)this.Owner).cfg.CheckFIO = ed_CheckFIO.Text;
            ((frmMine)this.Owner).cfg.CheckPhone = ed_CheckPhone.Text;
            ((frmMine)this.Owner).cfg.SelectAddr_Url = ed_SelectAddress.Text;
            ((frmMine)this.Owner).cfg.SearchAddr_Url = ed_SearchAddress.Text;
            */
            ((frmMine)this.Owner).cfg.isJSON = "False";
            

            ((frmMine)this.Owner).cfg.isUseDB = "False";

            ((frmMine)this.Owner).cfg.Http = edServ.Text;


            ABDLight.Properties.Settings.Default.MaxRowsToRead = textBox_MaxRowsToRead.Text;

            ABDLight.Properties.Settings.Default.Login = ((frmMine)this.Owner).cfg.Login;
            ABDLight.Properties.Settings.Default.TmpDir = ((frmMine)this.Owner).cfg.TmpDir;
            ABDLight.Properties.Settings.Default.defCountry = ((frmMine)this.Owner).cfg.defCountry;
            ABDLight.Properties.Settings.Default.edPwd = ((frmMine)this.Owner).cfg.edPass;

            /*
            ABDLight.Properties.Settings.Default.CheckEmail =  ((frmMine)this.Owner).cfg.CheckEmail;
            ABDLight.Properties.Settings.Default.CheckFIO = ((frmMine)this.Owner).cfg.CheckFIO;
            ABDLight.Properties.Settings.Default.CheckPhone = ((frmMine)this.Owner).cfg.CheckPhone;
            ABDLight.Properties.Settings.Default.SelectAddr_Url = ((frmMine)this.Owner).cfg.SelectAddr_Url;
            ABDLight.Properties.Settings.Default.SearchAddr_Url = ((frmMine)this.Owner).cfg.SearchAddr_Url;
            */

            ABDLight.Properties.Settings.Default.CheckEmail = edServ.Text + "/Services/IQDQ/CheckEmail?email=";
            ABDLight.Properties.Settings.Default.CheckFIO = edServ.Text + "/Services/IQDQ/CheckFIO?phrase=";
            ABDLight.Properties.Settings.Default.CheckPhone = edServ.Text + "/Services/IQDQ/CheckPhone?phone=phone_value&KLADR=KLADR_value";
            ABDLight.Properties.Settings.Default.SelectAddr_Url = edServ.Text + "/Services/IQDQ/SelectAddress?addr=";
            ABDLight.Properties.Settings.Default.SearchAddr_Url = edServ.Text + "/Services/IQDQ/SearchAddressDetail?addr=";


            //========================================
            ABDLight.Properties.Settings.Default.Table = ((frmMine)this.Owner).cfg.Table;
            

            //========================================

            ABDLight.Properties.Settings.Default.CheckOrgDubl = ((frmMine)this.Owner).cfg.CheckOrgDubl_Url;
            ABDLight.Properties.Settings.Default.AddressCleanASMX = ((frmMine)this.Owner).cfg.AddressCleanASMX_Url;

            ABDLight.Properties.Settings.Default.isJSON = ((frmMine)this.Owner).cfg.isJSON;
            ABDLight.Properties.Settings.Default.isUseDB = ((frmMine)this.Owner).cfg.isUseDB;

            //Полный коннекшн стринг
            ABDLight.Properties.Settings.Default.isWinAuth = "False";
            string SonnSrtFull = @"Data Source=" + ABDLight.Properties.Settings.Default.Server + ";Initial Catalog=" + ABDLight.Properties.Settings.Default.InitialCatalog + ";User ID=" + ABDLight.Properties.Settings.Default.UserID + ";Password=" + ABDLight.Properties.Settings.Default.Password + ";";
            ABDLight.Properties.Settings.Default.ABDLightDBConnectionString = SonnSrtFull;

            ABDLight.Properties.Settings.Default.Http = ((frmMine)this.Owner).cfg.Http.ToString();
           
            ABDLight.Properties.Settings.Default.Save();

            this.Close();
        }

        private void btnSeldir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.SelectedPath = edTmpDir.Text;
            if (dlg.ShowDialog() == DialogResult.OK) 
            {
                edTmpDir.Text = dlg.SelectedPath;
            }
        }

        private void frmSettings_Load(object sender, EventArgs e)
        {
            //==== Загрузка параметров в окно настроек (frmSettings)
            edLogin.Text = ((frmMine)this.Owner).cfg.Login;
            edPass.Text = ((frmMine)this.Owner).cfg.edPass;           
            cmbCountry.SelectedIndex = ((frmMine)this.Owner).cfg.defCountry;
            edTmpDir.Text = (((frmMine)this.Owner).cfg.TmpDir.Length == 0) ? (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) : ((frmMine)this.Owner).cfg.TmpDir;
            //==== Ссылки на сервисы:
            ed_CheckMail.Text = ABDLight.Properties.Settings.Default.CheckEmail;
            ed_CheckFIO.Text = ABDLight.Properties.Settings.Default.CheckFIO;
            ed_CheckPhone.Text = ABDLight.Properties.Settings.Default.CheckPhone;
            ed_SelectAddress.Text = ABDLight.Properties.Settings.Default.SelectAddr_Url;
            ed_SearchAddress.Text = ABDLight.Properties.Settings.Default.SearchAddr_Url;

            edServ.Text = ABDLight.Properties.Settings.Default.Http;  
            

            //============
            



            

           



            textBox_MaxRowsToRead.Text = ABDLight.Properties.Settings.Default.MaxRowsToRead;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void edLogin_TextChanged(object sender, EventArgs e)
        {

        }

        private void ed_DB_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnVwPwd_Click(object sender, EventArgs e)
        {
            if (edPass.PasswordChar == '*')
                edPass.PasswordChar = '\0';
            else
                edPass.PasswordChar = '*';

        }

        private void btnTestConn_Click(object sender, EventArgs e)
        {
            if (TestConnection()) MessageBox.Show(this, "Тестовое подключение завершилось удачно", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        public bool TestConnection()
        {
            string TestConn = edServ.Text + "/account/ServicePermission?logIn=" + HttpUtility.UrlEncode(edLogin.Text) + "&paSs=" + HttpUtility.UrlEncode(edPass.Text);

            try
            {
                string responsetext;
                try
                {
                    responsetext = new StreamReader(HttpWebRequest.Create(TestConn).GetResponse().GetResponseStream()).ReadToEnd();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Ошибка подключения!\nПроверьте подключение к сети и доступ к сервисам IQDQ!\nПри повторной ошибке обратитесь к администратору сети!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                //ServError Serv = new JavaScriptSerializer().Deserialize<ServError>(responsetext);

                if (responsetext.ToLower() != "ok")
                {
                    MessageBox.Show(this, "Ошибка подключения:\n" + responsetext + "\nОбратитесь к администратору сети!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch { }

            return true;
        }



        public class ServError
        {
            public string error { get; set; }
            public string msg { get; set; }

        }


    }
}
